using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using mojoPortal.Web;
using mojoPortal.Web.Framework;
using mojoPortal.Web.UI;
using log4net;
using mojoPortal.Business;
using eStore.Business;
using mojoPortal.Business.Commerce;
using mojoPortal.Business.WebHelpers.PaymentGateway;
using Resources;
using eStore.Helpers;
using GCheckout.Checkout;
using GCheckout.Util;
using System.Collections;

namespace eStore.UI
{

    public partial class CheckoutPage : mojoBasePage
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(CheckoutPage));

        protected int pageId = -1;
        protected int moduleId = -1;
        protected SiteUser siteUser;
        protected Store store;
        protected CultureInfo currencyCulture = CultureInfo.CurrentCulture;
        protected Cart cart;
        private List<CartProduct> cartProducts;
        private CommerceConfiguration commerceConfig;
        private const string PayPalExpressButtonImageUrl = "https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif";
        private bool canCheckoutWithoutAuthentication;
        private eStoreConfiguration config = new eStoreConfiguration();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (SiteUtils.SslIsAvailable()) SiteUtils.ForceSsl();

            if (!UserCanViewPage(moduleId))
            {
                SiteUtils.RedirectToAccessDeniedPage();
                return;
            }

            LoadSettings();

            if ((store == null) || (store.IsClosed))
            {
                WebUtils.SetupRedirect(this, SiteUtils.GetCurrentPageUrl());
                return;
            }

            if ((!canCheckoutWithoutAuthentication) && (!Request.IsAuthenticated))
            {
                WebUtils.SetupRedirect(this, SiteUtils.GetCurrentPageUrl());
                return;
            }

            SetupCss();
            PopulateLabels();
            PopulateControls();

        }

        private void PopulateControls()
        {
            if (!Page.IsPostBack)
            {
                PopulateYearList();
            }

            ShowCart();
            SetupPaymentUI();

        }

        private void ShowCart()
        {
            btnMakePayment.Enabled = false;
            if (commerceConfig.GoogleCheckoutIsEnabled)
            {
                if ((!commerceConfig.Is503TaxExempt) && (cart.HasDonations()))
                {
                    btnGoogleCheckout.Visible = true;
                    btnGoogleCheckout.Enabled = false;
                    lblGoogleMessage.Text = eStoreResources.GoogleCheckoutDisabledForDonationsMessage;
                    lblGoogleMessage.Visible = true;

                }
                else
                {
                    btnGoogleCheckout.Visible = true;
                }
            }
            else
            {
                btnGoogleCheckout.Visible = false;
            }


            if ((store == null) || (cart == null)) return;

            if (cartProducts != null)
            {
                rptCartItems.DataSource = cartProducts;
                rptCartItems.DataBind();
            }

            if (cart.SubTotal > 0) btnMakePayment.Enabled = true;

            litSubTotal.Text = StoreHelper.FormatPrice(cart.SubTotal.ToString(), currencyCulture);
            litDiscount.Text = StoreHelper.FormatPrice(cart.Discount.ToString(), currencyCulture);
            litOrderTotal.Text = StoreHelper.FormatPrice(cart.OrderTotal.ToString(), currencyCulture);

            pnlDiscount.Visible = (cart.Discount > 0);

            if ((cart.ShippingTotal == 0) && (cart.TaxTotal == 0) && (cart.Discount == 0))
            {
                pnlSubTotal.Visible = false;
            }


            if (cart.OrderInfo != null)
            {
                litBillingName.Text = cart.OrderInfo.BillingFirstName + @" " + cart.OrderInfo.BillingLastName;

                if (cart.OrderInfo.BillingCompany.Length > 0)
                {
                    litBillingCompany.Text = cart.OrderInfo.BillingCompany;
                }

                litBillingAddress1.Text = cart.OrderInfo.BillingAddress1;

                litBillingCity.Text = cart.OrderInfo.BillingCity;
                litBillingPostalCode.Text = cart.OrderInfo.BillingPostalCode;
                litBillingCountry.Text = cart.OrderInfo.BillingCountry;
                litBillingEmail.Text = @"<a href=""mailto:" + cart.OrderInfo.CustomerEmail + @""">" + cart.OrderInfo.CustomerEmail + @"</a>";
                litBillingTelephoneDay.Text = cart.OrderInfo.CustomerTelephoneDay;
                
            }

            if (!commerceConfig.PaymentGatewayUseTestMode) return;
            //pnp requires the name to be test user and the ccnumber to be 4111111111111111
            txtCardOwnerFirstName.Text = @"John";
            txtCardOwnerLastName.Text = @"Doe";
            txtCardNumber.Text = @"4721930402892796";
            txtCardSecurityCode.Text = @"456";

            ListItem item = ddExpireYear.Items.FindByValue(DateTime.UtcNow.AddYears(1).Year.ToString(CultureInfo.InvariantCulture));
            if (item == null) return;
            ddExpireYear.ClearSelection();
            item.Selected = true;
        }



        private void btnMakePayment_Click(object sender, EventArgs e)
        {
            //Page.Validate();

            if (
                (store != null)
                && (cart != null)
                && (IsValidForCheckout())
                )
            {
                IPaymentGateway gateway = commerceConfig.GetDirectPaymentGateway();
                if (gateway == null)
                {
                    lblMessage.Text = eStoreResources.PaymentGatewayNotConfiguredForDirectCardProcessing;
                    btnMakePayment.Enabled = false;
                    return;
                }
                if (gateway is PlugNPayPaymentGateway)
                {
                    gateway.MerchantInvoiceNumber = cart.CartGuid.ToString("N");
                    string CartItems = "";
                    int itemnum = 0;
                    foreach (CartProduct cproduct in cart.CartProducts)
                    {
                        itemnum++;
                        CartItems += string.Format("&item{1}={0}&cost{1}={2}&description{1}={3}&quantity{1}={4}", cproduct.ProductGuid, itemnum, cproduct.ProductPrice, cproduct.Name, cproduct.Quantity);
                    }
                    gateway.MerchantTransactionDescription = CartItems; //not sure if this is the intended purpose or not
                }

                gateway.CardType = ddCardType.SelectedValue;
                gateway.CardNumber = txtCardNumber.Text;
                gateway.CardExpiration = ddExpireMonth.SelectedValue + ddExpireYear.SelectedValue;
                gateway.ChargeTotal = cart.OrderTotal;
                gateway.CardSecurityCode = txtCardSecurityCode.Text;

                gateway.CardOwnerFirstName = txtCardOwnerFirstName.Text;
                gateway.CardOwnerLastName = txtCardOwnerLastName.Text;

                gateway.CardOwnerCompanyName = cart.OrderInfo.BillingCompany;
                gateway.CardBillingAddress = cart.OrderInfo.BillingAddress1
                    + " " + cart.OrderInfo.BillingAddress2;

                gateway.CardBillingCity = cart.OrderInfo.BillingCity;
                gateway.CardBillingState = cart.OrderInfo.BillingState;
                gateway.CardBillingPostalCode = cart.OrderInfo.BillingPostalCode;
                gateway.CardBillingCountry = cart.OrderInfo.BillingCountry;


                gateway.CardBillingCountryCode = cart.OrderInfo.BillingCountry;

                gateway.CardBillingPhone = cart.OrderInfo.CustomerTelephoneDay;
                gateway.CustomerIPAddress = SiteUtils.GetIP4Address();

                // this is where the actual request is made, it can timeout here
                bool executed;
                try
                {
                    executed = gateway.ExecuteTransaction();
                }
                catch (WebException ex)
                {
                    lblMessage.Text = commerceConfig.PaymentGatewayUseTestMode ? ex.Message : eStoreResources.PaymentGatewayCouldNotConnectMessage;
                    return;
                }

                string serializedCart = string.Empty;

                if (gateway is PayPalDirectPaymentGateway)
                {
                    // this is capturing of the serialized cart is not needed for other providers and I'm not sure its even needed for PayPal Direct
                    // it was needed for other paypal solutions. I just don't want to remove it until I'm sure
                    cart.SerializeCartProducts();
                    serializedCart = SerializationHelper.SerializeToString(cart);

                    gateway.LogTransaction(
                        siteSettings.SiteGuid,
                        store.ModuleGuid,
                        store.Guid,
                        cart.CartGuid,
                        cart.UserGuid,
                        "eStorePayPalDirect",
                        "DirectPayment",
                        serializedCart);

                }
                else
                {
                    gateway.LogTransaction(
                        siteSettings.SiteGuid,
                        store.ModuleGuid,
                        store.Guid,
                        cart.CartGuid,
                        cart.UserGuid,
                        string.Empty,
                        "eStoreCheckout",
                        serializedCart);
                }


                if (executed)
                {
                    switch (gateway.Response)
                    {
                        case PaymentGatewayResponse.Approved:
                            cart.LastUserActivity = DateTime.UtcNow;
                            cart.OrderInfo.CompletedFromIP = SiteUtils.GetIP4Address();
                            cart.OrderInfo.Completed = DateTime.UtcNow;
                            StoreHelper.EnsureUserForOrder(cart);
                            cart.Save();

                            //Order order = Order.CreateOrder(store, cart, gateway, store.DefaultCurrency, "CreditCard");
                            Order order = Order.CreateOrder(store, cart, gateway, siteSettings.GetCurrency().Code, "CreditCard");
                            StoreHelper.ClearCartCookie(cart.StoreGuid);

                            // send confirmation email
                            try
                            {
                                StoreHelper.ConfirmOrder(store, order);
                                Module m = new Module(store.ModuleId);
                                Order.EnsureSalesReportData(m.ModuleGuid, pageId, moduleId);
                            }
                            catch (Exception ex)
                            {
                                log.Error("error sending confirmation email", ex);
                            }

                            // redirect to order details
                            string redirectUrl = SiteRoot +
                                "/eStore/OrderDetail.aspx?pageid="
                                + pageId.ToString(CultureInfo.InvariantCulture)
                                + "&mid=" + moduleId.ToString(CultureInfo.InvariantCulture)
                                + "&orderid=" + order.OrderGuid;

                            WebUtils.SetupRedirect(this, redirectUrl);
                            return;

                        case PaymentGatewayResponse.Declined:

                            lblMessage.Text = eStoreResources.TransactionDeclinedMessage;

                            break;


                        case PaymentGatewayResponse.Error:

                            if (gateway.UseTestMode)
                            {
                                lblMessage.Text = gateway.LastExecutionException != null ? gateway.LastExecutionException.ToString() : gateway.RawResponse;
                            }
                            else
                            {
                                lblMessage.Text = eStoreResources.TransactionErrorMessage;
                            }

                            break;

                        case PaymentGatewayResponse.NoRequestInitiated:

                            lblMessage.Text = eStoreResources.TransactionNotInitiatedMessage;
                            break;
                    }
                }
                else
                {
                    lblMessage.Text = eStoreResources.TransactionNotInitiatedMessage;

                    if (gateway.LastExecutionException != null)
                    {
                        if (commerceConfig.PaymentGatewayUseTestMode)
                            lblMessage.Text = gateway.LastExecutionException.ToString();
                    }
                }

            }

            btnMakePayment.Text = eStoreResources.PaymentButton;
        }

        void btnGoogleCheckout_Click(object sender, ImageClickEventArgs e)
        {
            if (
                (store != null)
                && (cart != null)
                )
            { //&& (IsValidForCheckout()) ?

                const int cartTimeoutInMinutes = 30;

                CheckoutShoppingCartRequest Req = new CheckoutShoppingCartRequest(
                    commerceConfig.GoogleMerchantID,
                    commerceConfig.GoogleMerchantKey,
                    commerceConfig.GoogleEnvironment,
                    siteSettings.GetCurrency().Code,
                    cartTimeoutInMinutes);


                foreach (CartProduct cartProduct in cartProducts)
                {

                    Req.AddItem(
                        cartProduct.Name,
                        string.Empty,
                        cartProduct.ProductPrice,
                        cartProduct.Quantity);
                }

                //Req.AddMerchantCalculatedShippingMethod
                //Req.AnalyticsData
                //Req.ContinueShoppingUrl
                //Req.EditCartUrl

                //Req.RequestInitialAuthDetails
                //Req.AddParameterizedUrl

                // we need to serialize the cart and it items to xml here
                // so when we get it back from google
                // we can validate against the existing cart
                // as its possible items were added to the cart
                // after we passed the user to google

                //Req.MerchantPrivateData = cart.CartGuid.ToString();
                //cart.SerializeCartProducts();
                //Req.MerchantPrivateData = SerializationHelper.SerializeToSoap(cart);

                cart.SerializeCartProducts();
                MerchantData merchantData = new MerchantData
                                                {
                                                    ProviderName = "eStoreGCheckoutNotificationHandlerProvider",
                                                    SerializedObject =
                                                        SerializationHelper.RemoveXmlDeclaration(
                                                            SerializationHelper.SerializeToString(cart))
                                                };

                Req.MerchantPrivateData = SerializationHelper.RemoveXmlDeclaration(SerializationHelper.SerializeToString(merchantData));

                Req.RequestBuyerPhoneNumber = true;

                // flat rate shipping example
                //Req.AddFlatRateShippingMethod("UPS Ground", 5);

                //Add a rule to tax all items at 7.5% for Ohio
                //Req.AddStateTaxRule("NC", .15, true);
                //TODO: lookup tax 

                GCheckoutResponse Resp = Req.Send();

                if (Resp.IsGood)
                {
                    Response.Redirect(Resp.RedirectUrl, true);
                }
                else
                {
                    lblMessage.Text = Resp.ErrorMessage;
                }
            }

        }

        /// <summary>
        /// This is really a fallback method, it will not be executed in normal use of PayPalStandard because we are setting the postbackurl of the button
        /// to post directly to paypal, so this method should not fire unless somehow the page is manipulated to postback to itself or if using PayPalPro Express Checkout
        /// In this case, we just consolidate the cart into a buy now button.
        /// </summary>
        void btnPayPal_Click(object sender, ImageClickEventArgs e)
        {
            if (commerceConfig.PayPalUsePayPalStandard)
            {
                // should not reach here
                DoPayPalStandardCheckout();
            }
            else
            {
                DoPayPalExpressCeckout();
            }

        }


        private void DoPayPalStandardCheckout()
        {
            PayPalLog payPalLog = new PayPalLog
                                      {
                                          ProviderName = eStorePayPalReturnHandler.ProviderName,
                                          PDTProviderName = eStorePayPalPDTHandlerProvider.ProviderName,
                                          IPNProviderName = eStorePayPalIPNHandlerProvider.ProviderName,
                                          ReturnUrl = SiteRoot +
                                                      "/eStore/OrderDetail.aspx?pageid="
                                                      + pageId.ToString(CultureInfo.InvariantCulture)
                                                      + "&mid=" + moduleId.ToString(CultureInfo.InvariantCulture)
                                                      + "&orderid=" + cart.CartGuid,
                                          RequestType = "StandardCheckout"
                                      };

            cart.SerializeCartProducts();
            payPalLog.SerializedObject = SerializationHelper.SerializeToString(cart);

            //Currency currency = new Currency(store.DefaultCurrencyId);

            payPalLog.CartGuid = cart.CartGuid;
            payPalLog.SiteGuid = store.SiteGuid;
            payPalLog.StoreGuid = store.Guid;
            payPalLog.UserGuid = cart.UserGuid;
            payPalLog.CartTotal = cart.OrderTotal;
            payPalLog.CurrencyCode = siteSettings.GetCurrency().Code;

            payPalLog.Save();

            string payPalStandardUrl = StoreHelper.GetBuyNowUrl(
                payPalLog.RowGuid,
                cart,
                store,
                commerceConfig);

            WebUtils.SetupRedirect(this, payPalStandardUrl);

        }

        private void SetupPayPalStandardForm()
        {
            PayPalLog payPalLog = StoreHelper.EnsurePayPalStandardCheckoutLog(cart, store, SiteRoot, pageId, moduleId);
            if (payPalLog == null)
            {
                // this shouldn't happen but if we don't have the log then hide the button
                btnPayPal.Visible = false;
                return;
            }

            litPayPalFormVariables.Text = StoreHelper.GetCartUploadFormFields(
                payPalLog.RowGuid,
                cart,
                store,
                commerceConfig);

            btnPayPal.PostBackUrl = commerceConfig.PayPalStandardUrl;
        }



        private void DoPayPalExpressCeckout()
        {
            PayPalExpressGateway gateway
                = new PayPalExpressGateway(
                    commerceConfig.PayPalAPIUsername,
                    commerceConfig.PayPalAPIPassword,
                    commerceConfig.PayPalAPISignature,
                    commerceConfig.PayPalStandardEmailAddress)
                      {
                          UseTestMode = commerceConfig.PaymentGatewayUseTestMode,
                          MerchantCartId = cart.CartGuid.ToString(),
                          ChargeTotal = cart.OrderTotal
                      };

            string siteRoot = SiteUtils.GetNavigationSiteRoot();
            gateway.ReturnUrl = siteRoot + "/Services/PayPalReturnHandler.ashx";
            gateway.CancelUrl = siteRoot + Request.RawUrl;
            //Currency currency = new Currency(store.DefaultCurrencyId);
            gateway.CurrencyCode = siteSettings.GetCurrency().Code;
            gateway.OrderDescription = store.Name + " " + eStoreResources.OrderHeading;

            gateway.BuyerEmail = cart.OrderInfo.CustomerEmail;
            gateway.ShipToFirstName = cart.OrderInfo.DeliveryFirstName;
            gateway.ShipToLastName = cart.OrderInfo.DeliveryLastName;
            gateway.ShipToAddress = cart.OrderInfo.DeliveryAddress1;
            gateway.ShipToAddress2 = cart.OrderInfo.DeliveryAddress2;
            gateway.ShipToCity = cart.OrderInfo.DeliveryCity;
            gateway.ShipToState = cart.OrderInfo.DeliveryState;
            gateway.ShipToCountry = cart.OrderInfo.DeliveryCountry;
            gateway.ShipToPostalCode = cart.OrderInfo.DeliveryPostalCode;
            gateway.ShipToPhone = cart.OrderInfo.CustomerTelephoneDay;

            // this tells paypal to use the shipping address we pass in
            // rather than what the customer has on file
            // when we implement shippable products we'll do shipping calculations before
            // sending the user to paypal
            //gateway.OverrideShippingAddress = true;

            //commented out the above, we want user to be able to populate shipping info from their paypal account

            bool executed = gateway.CallSetExpressCheckout();
            if (executed)
            {
                //TODO: log the raw response
                if (gateway.PayPalExpressUrl.Length > 0)
                {
                    // record the gateway.PayPalToken
                    PayPalLog payPalLog = new PayPalLog
                                              {
                                                  RawResponse = gateway.RawResponse,
                                                  ProviderName = eStorePayPalReturnHandler.ProviderName,
                                                  ReturnUrl = siteRoot + Request.RawUrl,
                                                  Token = HttpUtility.UrlDecode(gateway.PayPalToken),
                                                  RequestType = "SetExpressCheckout"
                                              };
                    //payPalLog.PendingReason = gateway.PayPalExpressUrl;

                    cart.SerializeCartProducts();
                    payPalLog.SerializedObject = SerializationHelper.SerializeToString(cart);

                    payPalLog.CartGuid = cart.CartGuid;
                    payPalLog.SiteGuid = store.SiteGuid;
                    payPalLog.StoreGuid = store.Guid;
                    payPalLog.UserGuid = cart.UserGuid;

                    payPalLog.Save();

                    Response.Redirect(gateway.PayPalExpressUrl);

                }
                else
                {
                    if (commerceConfig.PaymentGatewayUseTestMode)
                        lblMessage.Text = gateway.RawResponse;
                }

            }
            else
            {
                lblMessage.Text = eStoreResources.TransactionNotInitiatedMessage;

                if (gateway.LastExecutionException != null)
                {
                    if (commerceConfig.PaymentGatewayUseTestMode)
                        lblMessage.Text = gateway.LastExecutionException.ToString();
                }
                else
                {
                    if (commerceConfig.PaymentGatewayUseTestMode)
                        lblMessage.Text = gateway.RawResponse;

                }
            }


        }



        private bool IsValidForCheckout()
        {
            bool result = true;

            int year = int.Parse(ddExpireYear.SelectedValue);
            int month = int.Parse(ddExpireMonth.SelectedValue);
            if (
                (year == DateTime.Now.Year)
                && (month < DateTime.Now.Month)
                )
            {

                result = false;
                lblMessage.Text += @" " + eStoreResources.CardExpiredWarning;

            }

            return result;

        }

        private void SetupPaymentUI()
        {
            switch (commerceConfig.PrimaryPaymentGateway)
            {
                case "PayPalDirect":
                case "Authorize.NET":
                case "PlugNPay":
                    frmCardInput.Visible = true;
                    break;
                default:
                    frmCardInput.Visible = false;
                    break;

            }

            if (!commerceConfig.CanProcessStandardCards)
            {
                frmCardInput.Visible = false;
            }


        }

        private void PopulateYearList()
        {
            DateTime date = DateTime.Today;

            for (int i = 0; i < 9; i++)
            {
                ListItem listItem
                    = new ListItem(date.Year.ToString(), date.Year.ToString());

                ddExpireYear.Items.Add(listItem);
                date = date.AddYears(1);

            }

        }

        private void PopulateLabels()
        {
            if (Master != null)
            {
                Control c = Master.FindControl("Breadcrumbs");
                if (c != null)
                {
                    BreadcrumbsControl crumbs = (BreadcrumbsControl)c;
                    crumbs.ForceShowBreadcrumbs = true;

                }
            }
            btnBack.Text = eStoreResources.BackButtonLabel;
            btnBack.PostBackUrl = SiteRoot + "/eStore/ConfirmOrder.aspx?pageid=" + pageId + "&mid=" + moduleId;
            moduleTitle.Header = eStoreResources.ReviewOrder;
            litCheckoutHeader.Text = eStoreResources.CheckoutHeader;
            litBillingHeader.Text = eStoreResources.CheckoutBillingInfoHeader;
            litOrderSummary.Text = eStoreResources.CheckoutOrderSummaryHeader;
            
            btnMakePayment.Text = eStoreResources.PaymentButton;
            btnMakePayment.Attributes.Add("onclick", "value='" + eStoreResources.PaymentButtonDisabledText + "';disabled = true;" + Page.ClientScript.GetPostBackEventReference(btnMakePayment, ""));

            btnPayPal.ImageUrl = PayPalExpressButtonImageUrl;
            btnGoogleCheckout.UseHttps = SiteUtils.SslIsAvailable();

            Title = SiteUtils.FormatPageTitle(siteSettings, CurrentPage.PageName + " - " + eStoreResources.Checkout);

            btnOrder.Text = eStoreResources.OrderButtonLabel;
        }



        private void ConfigureCheckoutButtons()
        {
            bool shouldShowPayPal = ShouldShowPayPal();
            bool shouldShowGoogle = ShouldShowGoogle();

            btnPayPal.Visible = shouldShowPayPal;
            btnGoogleCheckout.Visible = shouldShowGoogle;
            //litOr.Visible = (shouldShowPayPal || shouldShowGoogle);

            if (shouldShowGoogle)
            {
                if ((!commerceConfig.Is503TaxExempt) && (cart.HasDonations()))
                {
                    lblGoogleMessage.Text = eStoreResources.GoogleCheckoutDisabledForDonationsMessage;
                    lblGoogleMessage.Visible = true;
                    btnGoogleCheckout.Enabled = false;
                    //if (!Request.IsAuthenticated)
                    //{
                    //    PaymentAcceptanceMark mark = (PaymentAcceptanceMark)pam1;
                    //    mark.SuppressGoogleCheckout = true;
                    //}
                }

            }

            if ((shouldShowPayPal) && (commerceConfig.PayPalUsePayPalStandard))
            {
                SetupPayPalStandardForm();
            }


        }

        private void LoadSettings()
        {
            commerceConfig = SiteUtils.GetCommerceConfig();
            pnlCheckout.CssClass += " " + config.CustomCssClassSetting + "-cart";
            if (Request.IsAuthenticated)
            {
                siteUser = SiteUtils.GetCurrentSiteUser();
            }

            if (CurrentPage.ContainsModule(moduleId))
            {
                store = StoreHelper.GetStore();
            }


            if (store != null)
            {
                if (StoreHelper.UserHasCartCookie(store.Guid))
                {
                    cart = StoreHelper.GetCart();
                    if (cart != null)
                    {
                        cartProducts = cart.GetProducts();

                        canCheckoutWithoutAuthentication = store.CanCheckoutWithoutAuthentication(cart);

                        if ((cart.LastModified < DateTime.UtcNow.AddDays(-1)) && (cart.DiscountCodesCsv.Length > 0))
                        {
                            StoreHelper.EnsureValidDiscounts(store, cart);
                        }

                        if ((cart.UserGuid == Guid.Empty) && (siteUser != null))
                        {
                            cart.UserGuid = siteUser.UserGuid;
                            cart.Save();
                        }
                    }
                }

            }

            ConfigureCheckoutButtons();

        }

        private bool ShouldShowPayPal()
        {
            if (store == null) { return false; }
            if (cart == null) { return false; }
            if (cart.SubTotal == 0) { return false; }
            if (cart.OrderTotal == 0) { return false; }
            if (commerceConfig == null) { return false; }
            if ((!Request.IsAuthenticated) && (!canCheckoutWithoutAuthentication)) { return false; }
            if (!commerceConfig.PayPalIsEnabled) { return false; }



            return true;
        }

        private bool ShouldShowGoogle()
        {
            if (store == null) { return false; }
            if (cart == null) { return false; }
            if (cart.SubTotal == 0) { return false; }
            if (cart.OrderTotal == 0) { return false; }
            if (commerceConfig == null) { return false; }
            if ((!Request.IsAuthenticated) && (!canCheckoutWithoutAuthentication)) { return false; }
            if (!commerceConfig.GoogleCheckoutIsEnabled) { return false; }

            return true;
        }

        private void LoadParams()
        {
            pageId = WebUtils.ParseInt32FromQueryString("pageid", pageId);
            moduleId = WebUtils.ParseInt32FromQueryString("mid", true, moduleId);
            if (moduleId == -1)
            {
                moduleId = StoreHelper.FindStoreModuleId(CurrentPage);
            }

        }

        protected virtual void SetupCss()
        {
            // older skins have this
            if (Page.Master == null) return;
            StyleSheet stylesheet = (StyleSheet)Page.Master.FindControl("StyleSheet");
            if (stylesheet == null) return;
            if (stylesheet.FindControl("styleestore") != null) return;
            Literal cssLink = new Literal
                                  {
                                      ID = "styleestore",
                                      Text = @"<link href='"
                                             + SiteUtils.GetSkinBaseUrl()
                                             + @"styleestore.css' type='text/css' rel='stylesheet' media='screen' />"
                                  };

            stylesheet.Controls.Add(cssLink);
        }


        #region OnInit

        protected override void OnPreInit(EventArgs e)
        {
            AllowSkinOverride = true;
            base.OnPreInit(e);
        }

        protected override void OnInit(EventArgs e)
        {
            LoadParams();
            LoadPanels();
            base.OnInit(e);

            Load += Page_Load;

            btnMakePayment.Click += btnMakePayment_Click;

            btnGoogleCheckout.Click += btnGoogleCheckout_Click;
            btnPayPal.Click += btnPayPal_Click;
            btnOrder.Click += btnOrder_Click;
            SuppressPageMenu();
            SuppressGoogleAds();
        }

        void btnOrder_Click(object sender, EventArgs e)
        {
            cart.SerializeCartProducts();
            Order order = Order.CreateOrder(
                store,
                cart,
                siteSettings.GetCurrency().ToString(),
                "Email");
            try
            {
                StoreHelper.ConfirmOrder(store, order, currencyCulture);
            }
            catch (Exception ex)
            {
                log.Error("error sending confirmation email", ex);
            }
            string url = SiteRoot +
                    "/eStore/OrderDetail.aspx?pageid="
                    + pageId.ToString(CultureInfo.InvariantCulture)
                    + "&mid=" + moduleId.ToString(CultureInfo.InvariantCulture)
                    + "&orderid=" + cart.CartGuid;
            WebUtils.SetupRedirect(this, url);
        }

        private void LoadPanels()
        {
            Hashtable settings = ModuleSettings.GetModuleSettings(moduleId);
            config = new eStoreConfiguration(settings);
            LoadSideContent(config.ShowLeftPanelSetting, config.ShowRightPanelSetting, config.ShowTopPanelSetting, config.ShowBottomPanelSetting, config.ShowCenterPanelSetting);
        }
        #endregion
    }
}
